import { ProFormDependency, ProFormDigit, ProFormText } from '@ant-design/pro-components';
import React, { Key, useState } from 'react';
import { addItem, delItem, detailItem, getTreeList, updateItem } from '@/services/system/org';
import { getOptionBtn } from '@/util/table';
import { AUTH_TYPE, MENU_CODES } from '@/options';
import { getTreeKeyList } from '@/util/util';
import { useModel } from '@@/exports';
import useAuth from '@/hooks/useAuth';
import usePageVariable from '@/hooks/usePageVariable';
import MyPageContainer from '@/components/MyPageContainer';
import MyScrollTable from '@/components/MyScrollTable';
import MyForm from '@/components/MyForm';
import MyOrgSelect from '@/components/MyOrgSelect';
import MyUserSelect from '@/components/MyUserSelect';
import MyAddressCascader from '@/components/MyAddressCascader';
import useDefaultColumn from '@/hooks/useDefaultColumn';

type DataType = ORG_TYPE.Info;

const TableList: React.FC = () => {
  const { initialState } = useModel('@@initialState');
  const [expandedRowKeys, setExpandedRowKeys] = useState<Key[]>([]);
  const { insertAuth, updateAuth, detailAuth, delAuth } = useAuth(MENU_CODES.ORG);
  const defaultColumn = useDefaultColumn();
  const {
    formModel,
    setFormModel,
    formType,
    actionRef,
    formRef,
    currentRow,
    finishMsg,
    columns,
    changeForm,
    getFormTitle,
    delMsgOpen,
    setDelMsgOpen,
  } = usePageVariable<DataType>([
    defaultColumn.title,

    defaultColumn.directorId,
    {
      ...defaultColumn.mobile,
      hideInSearch: true,
    },
    {
      ...defaultColumn.createTime,
      sorter: false,
    },
    {
      ...defaultColumn.updateTime,
      sorter: false,
    },
    {
      ...defaultColumn.seq,
      sorter: false,
    },
    {
      title: '操作',
      valueType: 'option',
      render: (_, record) => [
        updateAuth && getOptionBtn(AUTH_TYPE.UPDATE, () => changeForm(record, '1')),
        detailAuth && getOptionBtn(AUTH_TYPE.DETAIL, () => changeForm(record, '2')),
        delAuth && getOptionBtn(AUTH_TYPE.DELETE, () => changeForm(record, '3')),
      ],
    },
  ]);
  const delCall = () =>
    finishMsg(async () => {
      const ret = await delItem(currentRow!.id);
      setDelMsgOpen(false);
      if (ret.success) actionRef.current?.reload();
    });

  const onFinish = async (value: DataType) => {
    if (formType === '2') {
      setFormModel(false);
      return;
    }
    await finishMsg(async () => {
      await (formType === '1'
        ? updateItem({
            ...value,
            id: currentRow!.id,
            // parentId: currentRow!.parentId, //添加无法修改机构的上级机构
          })
        : addItem(value));
      setFormModel(false);
      actionRef.current?.reload();
      formRef.current?.resetFields();
    });
  };
  return (
    <MyPageContainer modelOk={delCall} delMsgOpen={delMsgOpen} modelCancel={setDelMsgOpen}>
      <MyScrollTable<DataType, PageParams>
        actionRef={actionRef}
        request={async (params) => {
          const ret = await getTreeList(params);
          setExpandedRowKeys([...getTreeKeyList(ret.data)]);
          return ret;
        }}
        columns={columns}
        clickAdd={changeForm}
        isAdd={insertAuth}
        x="max-content"
        pagination={false}
        expandable={{
          expandedRowKeys,
        }}
      />
      <MyForm
        formRef={formRef}
        title={getFormTitle()}
        open={formModel}
        onOpenChange={setFormModel}
        onFinish={onFinish}
        readonly={formType === '2'}
        request={currentRow?.id ? () => detailItem(currentRow!.id) : undefined}
        initialValues={{
          seq: 0,
        }}
      >
        <ProFormText
          label="名称"
          name="title"
          fieldProps={{
            maxLength: 30,
            showCount: true,
          }}
          rules={[
            {
              required: true,
              message: '名称为必填项',
            },
          ]}
        />
        <MyOrgSelect
          label="上级"
          name="parentId"
          disabled={formType === '2' || initialState?.currentUser?.orgId === currentRow?.id}
          required={initialState?.currentUser?.orgId !== currentRow?.id}
          requiredMsg="上级为必填项"
          fieldProps={{
            onChange: () => {
              formRef.current?.setFieldsValue({ directorId: undefined });
            },
          }}
        />
        <ProFormDependency name={['parentId']}>
          {({ parentId }) => {
            return (
              <MyUserSelect
                required={false}
                params={{
                  orgId: parentId,
                  isChildrenAll: true,
                  isNotLike: true,
                }}
              />
            );
          }}
        </ProFormDependency>
        <ProFormText
          label="手机号码"
          name="mobile"
          rules={[
            {
              required: true,
              message: '手机号码为必填项',
            },
          ]}
        />

        <MyAddressCascader />
        <ProFormDigit label="排序" name="seq" />
      </MyForm>
    </MyPageContainer>
  );
};

export default TableList;
